//
// Created by zsj on 2019/12/22.
//

#include "rsa_file_op.h"

string generate_symm_key(int bits = 8) {
    // 每一位从0x00到0xFF
    string r;
    static uniform_int_distribution<unsigned> u(0, 255);
    static default_random_engine e;
    for (int i = 0; i < bits; i++) {
        r += (char) u(e);
    }

    return r;
}

string asym_encrypt(const string& _pub_key, const string& _plain) {
    // 因为方便所以只用DES算法对明文加密
    // 随机生成的密钥为8字节64位
    string _sym_key = generate_symm_key();

    // 对称加密
    auto* _sym_alg = new des_crypto();
    _sym_alg->set_key(_sym_key);
    _sym_alg->set_plain(_plain);
    string _symm_cipher = _sym_alg->execute(MODE_ENCRYPT);
    free(_sym_alg);

    // 再对密钥加密
    auto* _key_alg = new rsa_crypto();
    _key_alg->set_key(_pub_key);
    _key_alg->set_plain(_sym_key);
    string _key_cipher = _key_alg->execute(MODE_ENCRYPT);
    free(_key_alg);

    return _key_cipher + _symm_cipher;
}

string asym_decrypt(const string& _priv_key, const string& _cipher) {
    // 根据输入的私钥判定加密长度
    int _keylen = _rsa_keylen(_priv_key);

    // 获取密文前的加密后的对称钥
    string _key_cipher = _cipher.substr(0, _keylen);

    if (_key_cipher.length() < _keylen) {
        __err("解密文件出错。");
    }

    auto* _key_alg = new rsa_crypto();
    _key_alg->set_key(_priv_key);
    _key_alg->set_cipher(_key_cipher);
    string _sym_key = _key_alg->execute(MODE_DECRYPT);
    free(_key_alg);

    // 使用对称钥解密密文
    auto* _msg_alg = new des_crypto();
    _msg_alg->set_key(_sym_key);
    _msg_alg->set_cipher(_cipher.substr(_keylen));
    string _plain = _msg_alg->execute(MODE_DECRYPT);
    free(_msg_alg);

    return _plain;
}